﻿using System;
using System.Web;
using MyAMS.WebServer.Models;
using MyAMS.WebServer.Models.Extensions;

namespace MyAMS.WebServer.Extensions
{
    public static class HttpCookieCollectionExtensions
    {
        private const string anonymousUserCookieName = "anon";

        public static void ClearAnonymousUser(this HttpCookieCollection cookies)
        {
            cookies.Add(new HttpCookie(anonymousUserCookieName) { Expires = DateTime.Now.AddDays(-1) });
        }

        public static BaseUser GetAnonymousUser(this HttpCookieCollection cookies)
        {
            BaseUser user = null;

            HttpCookie cookie = cookies[anonymousUserCookieName];
            if (cookie != null)
            {
                user = user.FillFromSerlializedString(cookie.Value);
            }

            return user;
        }

        public static void SetAnonymousUser(this HttpCookieCollection cookies, BaseUser user)
        {
            HttpCookie cookie = new HttpCookie(anonymousUserCookieName, user.ToJson());
            cookie.Expires = DateTime.Now.AddDays(14);

            cookies.Add(cookie);
        }
    }
}
